<!-- 导航栏 -->
<script setup>
import { ref, reactive } from "vue";
import { ArrowDown, Bell, BellFilled } from "@element-plus/icons-vue";
import { useSelectStore } from "../stores/nav.js";
import { useRouter, useRoute } from "vue-router";
import { useUserStore } from "@/stores/userInfo.js";
import {
  uploadFile,
  updateUserInfo,
  reqUnreadCount,
  reqMessageList,
  reqReadMessage,
} from "@/api/api.js";
import { ElMessage } from "element-plus";
const router = useRouter();
const route = useRoute();
const store = useSelectStore();
const userStore = useUserStore();
/**控制个人信息对话框显示与隐藏 */
const dialogVisible = ref(false);
const dialogVisible2 = ref(false);
// const select = ref("");
const pages = [
  {
    label: "首页",
    path: "/home",
  },
  {
    label: "优待政策",
    path: "/news",
  },
  {
    label: "就业岗位",
    path: "/works",
  },
  {
    label: "事务办理",
    path: "/things",
  },
  {
    label: "意见与建议",
    path: "/suggestion",
  },
];

const form = reactive({
  id: "",
  /**身份证 */
  identityCard: "",
  /**头像 */
  avatar: "",
  /**手机 */
  phone: "",
  /**姓名 */
  realName: "",
  /**性别 */
  gender: "",
  /**出生日期 */
  birthDate: "",
  /**退伍日期 */
  retireDate: "",
  /**政治面貌 */
  politicalStatus: "",
  /**民族 */
  nationality: "",
  /**婚姻状况 */
  maritalStatus: "",
});
const fileList = ref([]);
const upload1 = ref();
/**未读消息 */
const count = ref(0);
/**消息列表 */
const messageList = ref([]);
/**前往登录页 */
const goLogin = () => {
  router.push("/login");
};

const goPage = (item) => {
  store.setSelect(item.label);
  router.push(item.path);
};

/**退出登录 */
const loginOut = () => {
  userStore.setUserInfo({});
  sessionStorage.removeItem("Token");
  sessionStorage.removeItem("user");
  router.push("/login");
};

/**保存表单 */
const saveForm = async () => {
  const res = await updateUserInfo(form);
  if (res.code == 200) {
    ElMessage.success("修改成功");
    userStore.setUserInfo(res.data);
    dialogVisible.value = false;
  } else {
    ElMessage.error(res.msg);
  }
};
/**回显个人信息 */
const setInfo = () => {
  form.avatar = userStore.userInfo.avatar;
  form.birthDate = userStore.userInfo.birthDate;
  form.gender = userStore.userInfo.gender;
  form.id = userStore.userInfo.id;
  form.identityCard = userStore.userInfo.identityCard;
  form.maritalStatus = userStore.userInfo.maritalStatus;
  form.nationality = userStore.userInfo.nationality;
  form.phone = userStore.userInfo.phone;
  form.politicalStatus = userStore.userInfo.politicalStatus;
  form.realName = userStore.userInfo.realName;
  form.retireDate = userStore.userInfo.retireDate;
  dialogVisible.value = true;
};

/**上传头像 */
const upload = async () => {
  console.log(fileList.value[0].raw);
  const res = await uploadFile({ file: fileList.value[0].raw });
  if (res.code == 200) {
    form.avatar = res.data;
  } else {
    ElMessage.error(res.msg);
  }
};

const handleExceed = (files) => {
  upload1.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  upload1.value.handleStart(file);
};

/**获取未读消息个数 */
const getCount = async () => {
  if (userStore.userInfo.id) {
    const res = await reqUnreadCount();
    if (res.code == 200) {
      count.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  }
};
/**获取消息列表 */
const getMessageList = async () => {
  if (userStore.userInfo.id) {
    const res = await reqMessageList();
    if (res.code == 200) {
      messageList.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  }
};

/**查看消息 */
const lookMessage = () => {
  dialogVisible2.value = true;
};

/**已读功能 */
const readMessage = async (ids) => {
  console.log(ids);

  const res = await reqReadMessage({ ids: ids });
  if (res.code == 200) {
    getMessageList();
    getCount();
  } else {
    ElMessage.error(res.msg);
  }
};

onMounted(() => {
  getCount();
  getMessageList();
});

watch(
  () => dialogVisible2,
  () => {
    if (dialogVisible2.value) {
      getMessageList();
    } else {
      getCount();
    }
  }
);

/**监听路由变化 */
watch(
  () => route.path,
  (newValue, oldValue) => {
    console.log(newValue, oldValue);
    if (newValue == "/home") {
      store.setSelect("首页");
    } else if (newValue == "/news") {
      store.setSelect("优待政策");
    } else if (newValue == "/works") {
      store.setSelect("就业岗位");
    } else if (newValue == "/things") {
      store.setSelect("事务办理");
    }
  }
);
</script>

<template>
  <div class="header">
    <div style="width: 60%; display: flex; align-items: center">
      <svg
        t="1735976981624"
        class="icon"
        viewBox="0 0 1076 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="5140"
        width="24"
        height="24"
      >
        <path
          d="M537.328622 0l166.44523 336.508834 372.692579 54.275618-269.568904 262.332156 63.321554 370.883392-332.890459-175.491166-331.081272 175.491166 63.321555-370.883392L0 390.784452l370.883392-54.275618z"
          fill="#DF4140"
          p-id="5141"
        ></path>
      </svg>
      <span style="font-weight: bold; font-size: 18px; margin-left: 10px">
        退役军人服务平台
      </span>
    </div>
    <div style="width: 40%" class="header-right">
      <div
        v-for="item in pages"
        :key="item.label"
        class="header-rightItem"
        :class="store.select == item.label ? 'active' : ''"
        @click="goPage(item)"
      >
        {{ item.label }}
      </div>
      <div v-if="userStore.userInfo?.realName">
        <el-dropdown style="margin-top: 2px">
          <span class="el-dropdown-link">
            {{ userStore.userInfo.realName }}
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="setInfo">个人信息</el-dropdown-item>
              <el-dropdown-item @click="loginOut">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div v-else class="header-rightItem" @click="goLogin">登录/注册</div>
      <el-badge :value="count" class="item" :show-zero="false">
        <el-icon
          size="24"
          color="#3B82F6"
          style="cursor: pointer"
          @click="lookMessage"
          ><BellFilled
        /></el-icon>
      </el-badge>
    </div>

    <el-dialog v-model="dialogVisible" title="个人信息" width="500">
      <el-form :model="form" label-position="top" label-width="180px">
        <div>
          <div style="display: flex; justify-content: center">
            <el-upload
              ref="upload1"
              class="upload-demo"
              :auto-upload="true"
              :http-request="upload"
              :show-file-list="false"
              :limit="1"
              :on-exceed="handleExceed"
              v-model:file-list="fileList"
            >
              <el-avatar :size="80" :src="form.avatar" />
            </el-upload>
          </div>
          <el-row :gutter="20" style="margin-top: 20px">
            <el-col :span="12">
              <el-form-item label="姓名" style="width: 100%">
                <el-input v-model="form.realName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证" style="width: 100%">
                <el-input v-model="form.identityCard"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px">
            <el-col :span="12">
              <el-form-item label="性别" style="width: 100%">
                <el-input v-model="form.gender"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出生日期" style="width: 100%">
                <el-date-picker
                  v-model="form.birthDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px">
            <el-col :span="12">
              <el-form-item label="手机号" style="width: 100%">
                <el-input v-model="form.phone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="退伍日期" style="width: 100%">
                <el-date-picker
                  v-model="form.retireDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px">
            <el-col :span="12">
              <el-form-item label="民族" style="width: 100%">
                <el-input v-model="form.nationality"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="政治面貌" style="width: 100%">
                <el-input v-model="form.politicalStatus"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="margin-top: 20px">
            <el-col :span="12">
              <el-form-item label="婚姻状况" style="width: 100%">
                <el-input v-model="form.maritalStatus"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveForm">保存修改</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible2" width="600">
      <template #header="{ close, titleId, titleClass }">
        <div
          class="my-header"
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div style="font-size: 18px">系统消息</div>
          <el-link
            :underline="false"
            type="primary"
            @click="
              readMessage(
                messageList.map((item) => {
                  return item.id;
                })
              )
            "
            >一键已读</el-link
          >
        </div>
        <div style="height: 500px; overflow-y: scroll; margin-top: 15px">
          <div class="messageCard" v-for="item in messageList">
            <div style="border-bottom: 1px solid #efefef; padding-bottom: 15px">
              {{ item.type }}&emsp;{{ item.createTime }}
            </div>

            <div style="margin-top: 15px" v-html="item.content"></div>
            <div style="display: flex; justify-content: flex-end">
              <el-link
                :underline="false"
                type="primary"
                v-if="item.status == '未读'"
                @click="readMessage([item.id])"
                >设为已读</el-link
              >
            </div>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
.header {
  display: flex;
  align-items: center;
  height: 72px;
  padding: 0 30px;
}
.header-right {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-rightItem:hover {
  color: red;
  cursor: pointer;
}
.active {
  color: red;
}
.el-dropdown-link {
  cursor: pointer;
}
.messageCard {
  border-radius: 15px;
  border: 1px solid #efefef;
  margin-bottom: 20px;
  padding: 15px;
}
</style>
